//go:build linux
// +build linux

package modbus

import (
	"fmt"
	"net"
	"syscall"
)

// setTCPKeepAliveProbes 设置探测间隔和次数（Linux实现）
func (sf *TCPClientProvider) setTCPKeepAliveProbes(tcpConn *net.TCPConn) error {
	// 获取底层文件描述符
	file, err := tcpConn.File()
	if err != nil {
		return fmt.Errorf("failed to get file descriptor: %v", err)
	}
	defer file.Close()

	fd := int(file.Fd())

	// 设置探测间隔（TCP_KEEPINTVL）
	intervalSec := int(sf.keepAliveInterval.Seconds())
	if err := syscall.SetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_KEEPINTVL, intervalSec); err != nil {
		return fmt.Errorf("failed to set TCP_KEEPINTVL: %v", err)
	}

	// 设置探测次数（TCP_KEEPCNT）
	if err := syscall.SetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_KEEPCNT, sf.keepAliveProbes); err != nil {
		return fmt.Errorf("failed to set TCP_KEEPCNT: %v", err)
	}

	sf.Debugf("Linux TCP Keep-Alive probes configured: interval=%ds, count=%d", intervalSec, sf.keepAliveProbes)
	return nil
}